package com.tuocent.dagv2.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tuocent.dagv2.common.AjaxResult;
import com.tuocent.dagv2.common.utils.SnowFlakeID;
import com.tuocent.dagv2.entity.Dictionary;
import com.tuocent.dagv2.mapper.DictionaryMapper;
import com.tuocent.dagv2.service.IDictionaryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 数据词典 服务实现类
 * </p>
 *
 * @author Vincent
 * @since 2025-07-30
 */
@Service
public class DictionaryServiceImpl extends ServiceImpl<DictionaryMapper, Dictionary> implements IDictionaryService {

    @Resource
    private SnowFlakeID snowFlakeID;

    @Override
    public AjaxResult getDictionaryData(String classId) {
        List<Dictionary> dictInfo = list(new QueryWrapper<Dictionary>()
                .eq("classid", classId)
                .orderByAsc("idx+0")
                .orderByAsc("length(code)")
                .orderByAsc("code"));
        return AjaxResult.success(dictInfo);
    }

    @Override
    public String setDictData(Model model, String id, String classId) {
        Dictionary dictInfo = getById(id);
        if (dictInfo == null) {
            dictInfo = new Dictionary();
            dictInfo.setClassid(classId);
        }
        model.addAttribute("dictInfo", dictInfo);
        return "/basic/setDataDict";
    }

    @Override
    public AjaxResult saveDataDict(Dictionary data) {
        if (data == null) {
            AjaxResult.error("没有需要保存的数据");
        }
        if (data.getName() == null || "".equals(data.getName())) {
            return AjaxResult.error("请输入词典名称");
        }
        if (data.getCode() == null || "".equals(data.getCode())) {
            return AjaxResult.error("请输入词典的值");
        }
        if (data.getId() == null) {
            data.setId(snowFlakeID.getId());
        }
        if (count(new QueryWrapper<Dictionary>()
                .eq("classid", data.getClassid())
                .eq("name", data.getName())
                .ne("id", data.getId())) > 0) {
            return AjaxResult.error("词典名称" + data.getCode() + "已存在");
        }
        if (count(new QueryWrapper<Dictionary>()
                .eq("classid", data.getClassid())
                .eq("code", data.getCode())
                .ne("id", data.getId())) > 0) {
            return AjaxResult.error("词典值" + data.getCode() + "已存在");
        }
        return saveOrUpdate(data) ? AjaxResult.success("保存数据成功") : AjaxResult.error("保存数据失败");
    }

    @Override
    public AjaxResult delDataDict(Map<String, String> data) {
        String id = data.getOrDefault("id", "");
        return removeById(id) ? AjaxResult.success("删除数据成功") : AjaxResult.error("删除数据失败");
    }
}
